<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Common\Model;

use Think\Model\RelationModel;

/**
 * 企业合同
 */
class ContractModel extends RelationModel {

    protected $_link = array(
        'mapping_type' => self::BELONGS_TO,
        'class_name' => 'business',
        'foreign_key ' => 'bus_id'
    );

    /**
     * 生成【企业合同】编号
     * @param string $date
     * @return type
     * @todo 逻辑：
     * 长度：15
     * 格式：'ZGY' + YYYYmmdd000X,
     * 示例：ZGY201609280002
     * S Q L：
     * select substr(number,4,8) as `no_date` ,MAX(CONVERT(substr(number,12),signed)) as `Max_no`
      from contract
      group by `no_date`;
     */
    public function createNo($date = '') {
        $sql_having = '';
        if (!empty($date)) {
            if (strlen($date) == 10) {
                $no_date = date('Ymd', $date);
            } elseif (strlen($date) == 8) {
                $no_date = date('Ymd', strtotime($date));
            }
            $no_date = !empty($no_date) ? $no_date : date('Ymd', time());
            if (!empty($no_date)) {
                $sql_having = 'no_date = ' . $no_date;
            }
        }
        $data = $this->field("substr(number,4,8) as `no_date` ,MAX(CONVERT(substr(number,12),signed)) as `max_no`")
                ->group('no_date')
                ->having($sql_having)
                ->find();
        if (!empty($data)) {
            $no = $data['max_no'] + 1;
        } else {
            $no = 1;
        }
        $no = sprintf('%04d', $no);
        $prefix = C('CONTRACT_PREFIX');
        $prefix = empty($prefix) ? 'ZGY' : $prefix;
        return $prefix . $no_date . $no;
    }

}
